package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.RedisConstants.LOCK_SHOP_KEY;

@Slf4j
@Component
public class CacheClient {

    StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    // 1. 将java对象序列化为json，并存储到String类型的key中，且可以设置TTL过期时间
    public void set(String key, Object obj, Long time, TimeUnit unit) {
        String data = JSONUtil.toJsonStr(obj);
        stringRedisTemplate.opsForValue().set(key, data, time, unit);
    }

    // 2. 将java对象序列化为json，并存储到String类型的key中，且可以设置逻辑过期时间，用于处理缓存击穿问题
    public void setWithLogicalExpire(String key, Object obj, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(obj);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    // 3. 指定key查询，并反序列化为指定类型，利用缓存空值的方式来解决缓存穿透问题
    public <R, ID> R queryWithPassThrough(
            String keyPrefix, ID id, Class<R> type, Function<ID, R> dbfallBack,
            Long time, TimeUnit unit) {
        // 凭借Rediskey
        String key = keyPrefix + id;
        // 查询redis中的数据
        String data = stringRedisTemplate.opsForValue().get(key);
        // 判断是否存在
        if (null != data && !"".equals(data)) {
            return JSONUtil.toBean(data, type);
        }
        // 判断命中的是否是空值
        if (null != data) {
            return null;
        }
        // 不存在查询数据库
        R rData = dbfallBack.apply(id);
        // 判断数据库中是否存在
        if (null == rData) {
            return null;
        }
        // 将数据存储到redis中
        this.set(key, rData, time, unit);
        return rData;
    }


    // 4. 指定key查询，并反序列化为指定类型，需要利用逻辑过期解决 缓存击穿问题
    private static final ExecutorService CACHE_BUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public <R, ID> R queryWithLogicalExpire(
            String keyPrefix, ID id, Class<R> type, Function<ID, R> dbfallBack,
            Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        // 1. 根据商品id去redis中查询数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);
//        System.out.println(shopJson);
        // 2. 未命中直接返回
        if (null == shopJson || "".equals(shopJson)) {
            return null;
        }

        // 命中，将json转为对象类
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
//        System.out.println(r.toString());
        // 判断信息是否过期
        if (null != expireTime && expireTime.isAfter(LocalDateTime.now())) {
            // 未过期，返回商铺信息
            return r;
        }
        // 过期，尝试获取互斥锁,并重建缓存
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryGetLock(lockKey);

        // 判断是否获取锁成功
        if (isLock) {
            RedisData checkRedisData = checkRedisData(key, RedisData.class);
            LocalDateTime expireTime1 = checkRedisData.getExpireTime();
            if (null != expireTime1 && expireTime1.isAfter(LocalDateTime.now()))
                return JSONUtil.toBean((JSONObject) redisData.getData(), type);
            else
                // 获取互斥锁成功，开启独立线程
                CACHE_BUILD_EXECUTOR.submit(() -> {
                    try {
                        // 1、 从数据库查询数据
                        R r1 = dbfallBack.apply(id);
                        // 写入redis
                        RedisData redisData1 = new RedisData();
                        redisData1.setData(r1);
                        redisData1.setExpireTime(LocalDateTime.now().plusSeconds(10));
                        this.set(key, JSONUtil.toJsonStr(redisData1), time, unit);
                    } catch (Exception e) {
                        throw new RuntimeException();
                    } finally {
                        unlock(lockKey);
                    }
                });
        }

        // 获取互斥锁失败,返回过期的商品信息
        return r;
    }

    private boolean tryGetLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

    public <T> T checkRedisData(String key, Class<T> beanClass) {
        String data = stringRedisTemplate.opsForValue().get(key);
        //        2. 存在直接返回
        if (null != data && !"".equals(data)) {
            return JSONUtil.toBean(data, beanClass);
        } else {
            return null;
        }
    }


}
